package com.qiuzhiyi.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.text.InputFilter;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.li.utils.InputFilterUtil;
import com.li.widget.CircleImageView;
import com.li.widget.TopNavigationBar;
import com.qiuzhiyi.R;
import com.qiuzhiyi.base.QZYBaseActivity;
import com.qiuzhiyi.cache.HumanCache;
import com.qiuzhiyi.dialogs.ChooseDialog;
import com.qiuzhiyi.dialogs.DateDialog;
import com.qiuzhiyi.item.BaseItem;
import com.qiuzhiyi.item.HumanItem;
import com.qiuzhiyi.net.ObservableHelper;
import com.qiuzhiyi.net.RetrofitHelper;
import com.qiuzhiyi.net.SelectorObserver;
import com.zhihu.matisse.Matisse;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;


/**
 * Author: Li
 * Date: 2017/11/14 0014
 * Description: 完善注册信息
 */

public class PerfectRegisterInfoActivity extends QZYBaseActivity {

    private static final int REQUEST_CODE_PERMISSION = 241;
    private static final int REQUEST_CODE_CHOOSE = 0;
    @BindView(R.id.top_navigation)
    TopNavigationBar mTopNavigation;
    @BindView(R.id.img_avatar)
    CircleImageView mImgAvatar;
    @BindView(R.id.et_nick)
    EditText mEtNick;
    @BindView(R.id.txt_sex)
    TextView mTxtSex;
    @BindView(R.id.txt_birth)
    TextView mTxtBirth;
    @BindView(R.id.txt_save)
    TextView mTxtSave;
    private ChooseDialog mDialogSex;
    private DateDialog mDateDialog;
    private String mAccount;
    private String mPwd;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_perfect_register_info;
    }

    @Override
    protected void initSth() {
        super.initSth();
        mTopNavigation.setNavigationBarListener(this);
        mAccount = getIntent().getStringExtra("account");
        mPwd = getIntent().getStringExtra("pwd");
        mEtNick.setFilters(new InputFilter[]{new InputFilterUtil.NoEmojiFilter()});
        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED
                || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(mActivity, new String[]{
                    Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
            }, REQUEST_CODE_PERMISSION);
        }
    }

    @OnClick({R.id.img_avatar, R.id.txt_sex, R.id.txt_birth, R.id.txt_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_avatar:
//                if (mDialogPhoto == null) {
//                    mDialogPhoto = new ChooseDialog(mContext, new ChooseDialog.OnChooseListener() {
//                        @Override
//                        public void onChoose(String content, int which) {
//                            Matisse.from(mActivity)
//                                    .choose(MimeType.allOf())
//                                    .countable(false)
//                                    .capture(true)
//                                    .captureStrategy(
//                                            new CaptureStrategy(true, "com.qiuzhiyi.fileprovider"))
//                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
//                                    .thumbnailScale(0.85f)
//                                    .imageEngine(new GlideEngine())
//                                    .forResult(REQUEST_CODE_CHOOSE);
//                        }
//                    }, "设置头像", new String[]{"选择本地图片", "拍照"});
//                }
//                mDialogPhoto.show();

                break;
            case R.id.txt_sex:
                if (mDialogSex == null) {
                    mDialogSex = new ChooseDialog(mContext, new ChooseDialog.OnChooseListener() {
                        @Override
                        public void onChoose(String content, int which) {
                            mTxtSex.setText(content);
                        }
                    }, "请选择性别", new String[]{"男", "女"});
                }
                mDialogSex.show();
                break;
            case R.id.txt_birth:
                if (mDateDialog == null) {
                    mDateDialog = new DateDialog(mContext, new DateDialog.OnDateChooseListener() {
                        @Override
                        public void onDateChoose(String date) {
                            mTxtBirth.setText(date);
                        }
                    });
                }
                mDateDialog.show();
                break;
            case R.id.txt_save:

                if (isEmpty(mAccount) || isEmpty(mPwd) || isEmpty(mTxtSex) || isEmpty(mTxtBirth) || isEmpty(mEtNick)) {
                    showToast("请完善用户信息");
                    return;
                }
                register(mAccount,
                        mPwd,
                        mTxtSex.getText().equals("男") ? "1" : "2",
                        mEtNick.getText().toString(),
                        mTxtBirth.getText().toString());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mImgAvatar.setImageURI(Matisse.obtainResult(data).get(0));
        }
    }

    private void register(String account, String pwd, String sex, String nickname, String birthday) {

        Map<String, String> map = new HashMap<>();
        map.put("humanAccount", account);
        map.put("humanPassword", pwd);
        map.put("humanSex", sex);
        map.put("humanQuestion", nickname);
        map.put("humanAnswer", birthday);
        ObservableHelper.createObservable(RetrofitHelper.createService().register(map))
                .subscribe(new SelectorObserver<BaseItem<HumanItem>>() {
                    @Override
                    protected void onErrorCodeInfo(String code, String info) {
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseItem<HumanItem> humanItemBaseItem) {
                        login(mAccount, mPwd);
                    }

                    @Override
                    protected void onFinish() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog("正在注册");
                    }
                });
    }

    /**
     * 登录
     *
     * @param account  账号
     * @param password 密码
     */
    private void login(String account, String password) {
        Map<String, String> map = new HashMap<>();
        map.put("humanAccount", account);
        map.put("humanPassword", password);
        map.put("loginStatus","2");
        ObservableHelper.createObservable(RetrofitHelper.createService().loginWithPwd(map))
                .subscribe(new SelectorObserver<BaseItem<HumanItem>>() {
                    @Override
                    protected void onErrorCodeInfo(String code, String info) {
                        showToast(info);
                    }

                    @Override
                    protected void onSuccess(BaseItem<HumanItem> humanItemBaseItem) {
                        HumanItem item = humanItemBaseItem.getObjValue();
                        HumanCache.saveHumanInfo(mContext, item);

                        showToast("登陆成功");
                        finish();
//                        startThenFinish(MainActivity.class);
                    }

                    @Override
                    protected void onFinish() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                        showLoadingDialog("正在登录");
                    }
                });

    }
}
